package com.example.interesting.distributed.log.realize.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.interesting.distributed.log.realize.constant.LogConstants;
import org.slf4j.MDC;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: traceId设置工具类
 * @Author: fyw
 * @Date: 2024/4/5 15:14
 * @History
 */
public class LogTraceInit implements EnvironmentAware {
    private static Environment environment;


    @Override
    public void setEnvironment(Environment environment) {
        LogTraceInit.environment = environment;
    }

    /**
     * 填充MDC里面的map
     */
    public static void fillTraceId(Map<String, String> headers) {
        //上级服务名称
        String parentServiceName = headers.get(LogConstants.PARENT_SERVICE_NAME);
        if (StrUtil.isBlank(parentServiceName)) {
            headers.put(LogConstants.PARENT_SERVICE_NAME, environment.getProperty("spring.application.name"));
        }
        //日志唯一标识
        String traceId = headers.get(LogConstants.LOG_TRACE_ID);
        if (StrUtil.isBlank(traceId)) {
            headers.put(LogConstants.LOG_TRACE_ID, IdUtil.fastSimpleUUID());
        }
        //放入MDC日志
        MDC.setContextMap(headers);
    }

    /**
     * 替换服务名称
     */
    public static Map<String, String> replaceServiceName() {
        //从MDC中获取filter塞如的日志请求头信息
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        if (copyOfContextMap == null) {
            copyOfContextMap = new HashMap<>();
        }
        copyOfContextMap.put(LogConstants.PARENT_SERVICE_NAME, environment.getProperty("spring.application.name"));
        return copyOfContextMap;
    }

}
